package org.xx.armory.spring5.mvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.xx.armory.commons.ForLogging;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST;

public class AddAuthenticationToViewInterceptor
        implements WebRequestInterceptor {
    @ForLogging
    private final Logger logger = LoggerFactory.getLogger(AddAuthenticationToViewInterceptor.class);

    @Override
    public void preHandle(
            WebRequest request
    )
            throws Exception {
    }

    @Override
    public void postHandle(
            WebRequest request,
            ModelMap model
    )
            throws Exception {
        var token = SecurityContextHolder.getContext().getAuthentication();
        if (token != null && token.isAuthenticated() && !(token instanceof AnonymousAuthenticationToken)) {
            logger.trace("Add token {} to view", token);
            request.setAttribute("token", token, SCOPE_REQUEST);
        } else {
            logger.trace("No valid token");
        }
    }

    @Override
    public void afterCompletion(
            WebRequest request,
            Exception ex
    )
            throws Exception {
    }
}
